package com.ls.rbac.security;

/**
 * created by liush on 2025/6/27
 **/


import cn.hutool.json.JSONUtil;


import com.ls.rbac.entity.User;
import com.ls.rbac.utils.RedisUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;

@Component
@Slf4j
public class LogoutHandler implements LogoutSuccessHandler {

    @Resource
    private RedisUtils redisUtils;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        SecurityContextHolder.clearContext();
        User user = (User) authentication.getPrincipal();
        String keyToken = "login:" + user.getId();
        String userInfoKey = "login:info:" + user.getId();
        String permissionKey = "permissions:" + user.getId();
        redisUtils.delete(keyToken);
        redisUtils.delete(userInfoKey);
        redisUtils.delete(permissionKey);
        AuthenticationResult authResult = new AuthenticationResult(
                null, HttpStatus.OK.value(), "注销成功",
                null, null);
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json;charset=UTF-8");
        String result = JSONUtil.toJsonStr(authResult);
        response.getWriter().write(result);
        response.getWriter().flush();
    }
}
